﻿@page "/docs/{fileName}"
@page "/docs"

@using AntBlazor.Docs.Services

@inject NavigationManager NavigationManager
@inject ILanguageService LanguageService
@inject DemoService DemoService

<MainContent>
    <article class="markdown">
        <Markdown docUrl="@docUrl"></Markdown>
    </article>
</MainContent>

@code {

    [Parameter] public string fileName { get; set; }

    string docUrl { get; set; }

    string currentLanguage => LanguageService.CurrentCulture.Name;

    protected override async Task OnInitializedAsync()
    {
        await SetDocUrl();
        NavigationManager.LocationChanged += async (_, args) => await SetDocUrl();
    }

    private async ValueTask SetDocUrl()
    {
        if (!string.IsNullOrEmpty(fileName))
        {
            var baseUrl = NavigationManager.ToAbsoluteUri(NavigationManager.BaseUri);
            docUrl = new Uri(baseUrl, $"docs/{fileName}.{currentLanguage}.md").ToString();
            StateHasChanged();
        }
        else
        {
            var currentUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri);
            var newUrl = currentUrl.IndexOf('/') > 0 ? currentUrl.Substring(currentUrl.IndexOf('/') + 1) : currentUrl;
            var menus = await DemoService.GetMenuAsync();
            var current = menus.FirstOrDefault(x => x.Url == newUrl);
            if (current != null)
            {
                NavigationManager.NavigateTo($"{currentLanguage}/{current.Children[0].Url}");
            }
        }
    }

}
